$(document).ready(function() {
	if(bugs.music.initOnLoad)
		bugs.music.init();
});

bugs.music = {
	MV_QUALITY_FULLHD : "FULLHD",
	MV_QUALITY_HD : "HD",
	MV_QUALITY_SD : "SD",
	MV_QUALITY_MP4 : "MP4",
	
	playerController : null,
	flashInstalled : false,
	flashPopup : null,
	initOnLoad : true,

	init : function(musicController, mvController) {
		var top = $(document).scrollTop();
		$("<div><div id=\"BugsPlayerController\"></div></div>").css({position : "absolute", top : top, left : 0, width : 10, height : 10}).appendTo("body");
		
		var flashvars = {
			musicController : musicController,
			mvController : mvController
		};
		
		var params = {
			wmode : "transparent",
			allowScriptAccess : "always" 
		};
		
		var attr = {
			id : "BugsPlayerController"
		};
		
		this.flashInstalled = swfobject.hasFlashPlayerVersion("10"); 
		if(this.flashInstalled) {
			swfobject.embedSWF(g_urlSwf + "/BugsPlayerController.swf?version=201211042302", "BugsPlayerController", "100%", "100%", "10.0.0", "expressInstall.swf", flashvars, params, attr);
		} else {
			var html = "<p>벅스 플레이어는 Adobe Flash Player 10<br/> 이상을 설치하셔야 사용 가능합니다.<br />" + 
				"<span><a href=\"http://www.adobe.com/go/getflashplayer\" onclick=\"return bugs.utils.openWindow(this);\">Flash 플레이어 받기</a></span></p>" +
				"<div class=\"btnArea\"><span class=\"button typeME\"><a href=\"#\" type=\"cancel\">닫기</a></span></div>";
			
			this.flashPopup = new bugs.ui.popup(html, {
				css : "layerDownDRM", 
				title : bugs.ui.TITLE_LOGO
			});
		}
	},
	getPlayerController : function() {
		if(this.playerController) return this.playerController;
		
		var controller = $("#BugsPlayerController")[0];
		if(!controller || controller == "DIV" || (typeof(controller.isPlayerExist) == "undefined" && typeof(controller.isMvPlayerExist) == "undefined")) return null;
		
		return (this.controller = controller);
	},
	listen : function(trackId, playForce, param) {
			
		if(typeof trackId == "undefined") return;
		if(typeof trackId == "string") {
		} else if(typeof trackId == "object") {
			var trackIdStr = "";
			if(trackId.length == 0) {
				bugs.ui.showAlert("음악을 선택하여 주십시오.", {css : "layerAdultNotice"});
				return;
			}
			for(var i=0;i < trackId.length;i++) {
				trackIdStr += $(trackId[i]).val();
				if(i < trackId.length - 1) trackIdStr +=",";
			}
			//alert(trackIdStr + " 재생");
			trackId = trackIdStr;
		}
		
		if(!this.flashInstalled) {
			this.flashPopup.show();
			return;
		}
		
		var controller = this.getPlayerController();
		if(!controller) return;
		if(controller.isPlayerExist()) {
			controller.addTrack(trackId, playForce);
			return true; // return 이 없으면 팝업이 없다고 판단하므로 
		}
		else {
			if(typeof trackId != "string"){
				trackId = trackId+"";
			}
			if(trackId.split(",").length > 50){
				var frm = null;
				if($("form[playerForm]").attr("name") == "playerFrm"){
					frm = $("form[playerForm]")[0];
				}else{
					frm = document.createElement("form");
					frm.name = "playerFrm";
					frm.action = g_urlMusic + "/newPlayer";
					frm.method = "POST";
					frm.target = "BugsPlayer";
					
					var ip = document.createElement("input");
					ip.type = "hidden";
					ip.name = "trackId";
					ip.value = trackId;
					frm.appendChild(ip)
					frm.insertBefore(ip);
					document.body.appendChild(frm);
				}
				
				window.open('', "BugsPlayer", "width=384,height=667,resizable=0");
				frm.submit();
				
			}else{
				var url = g_urlMusic + "/newPlayer?trackId=" + trackId;
				if (typeof(param) != "undefined")
					url += "&"+param;
				var popup = window.open(url, "BugsPlayer", "width=384,height=667,resizable=0");
				return popup;
			}
		}
	},
	
	openBugsRadio : function(){
		if(!this.flashInstalled) {
			this.flashPopup.show();
			return;
		}
		
		var controller = this.getPlayerController();
		if(!controller) return;
		
		if(!controller.isRadioExist()) {
			window.open(g_urlMusic + "/newRadio?wl_ref=radio_1", "BugsRadio", "width=368,height=614,resizable=0");
		}
	},
	
	listenRadio : function(keyword, playForce) {
		if(typeof keyword == "undefined") return;
		if(typeof keyword == "string") {
		} else if(typeof keyword == "object") {
			if(keyword ==  ""){
				return;
			}
		}
		
		if(!this.flashInstalled) {
			this.flashPopup.show();
			return;
		}
		
		var controller = this.getPlayerController();
		if(!controller){
			return;
		}
		
		if(controller.isRadioExist() && !playForce) {
			if(keyword == ""){
				return;
			}
			controller.radioSearch(keyword);
		
		}else if(controller.isRadioExist() && playForce){
			controller.createChannel(keyword);
		
		}else {
			window.open(g_urlMusic + "/newRadio?keyword=" + encodeURIComponent(keyword)+"&playForce="+playForce+"&wl_ref=radio_1", "BugsRadio", "width=368,height=614,resizable=0");
		}
	},
	
	
	listenRadioFromSeed : function(seed,type) {
		if(type == "" || typeof type == "undefined" || typeof type == "object"){
			return;
		}
		
		if(type != "track" && type != "artist"){
			return;
		}
		
		if(typeof seed == "undefined") return;
		if(typeof seed == "string") {
		} else if(typeof seed == "object") {
			if(seed ==  ""){
				return;
			}
		}
		
		if(!this.flashInstalled) {
			this.flashPopup.show();
			return;
		}
		
		var controller = this.getPlayerController();
		if(!controller){
			return;
		}
		
		if(controller.isRadioExist()){
			if(type == "track"){
				controller.createChannelTrack(seed);
			}else{
				controller.createChannelArtist(seed);
			}
			
		}else {
			window.open(g_urlMusic + "/newRadio?seed=" + seed+"&type="+type+"&wl_ref=radio_1", "BugsRadio", "width=368,height=614,resizable=0");
		}
	},
	
	showRadioListenList : function(){
		if(!this.flashInstalled) {
			this.flashPopup.show();
			return;
		}
		
		var controller = this.getPlayerController();
		if(!controller){
			return;
		}
		
		if(controller.isRadioExist()) {
			controller.showLastStation();
		}else{
			window.open(g_urlMusic + "/newRadio?wl_ref=radio_1", "BugsRadio", "width=368,height=614,resizable=0");
		}
	},
	addTrackToMyAlbum : function(btn,track_id,type) {
		//alert();
		if(!g_isLogged) {
			bugs.ui.showLoginLayer();
			return;
		}
		else
		{
			//alert('here')
			playlists.showPlaylistLayer($(btn), track_id, type);
		}
	}, 		
	_loadController : function(trackId, mvId, playForce) {
		// swfobject 없으면 추가
		if(typeof(swfobject) == "undefined") {
			$("head").append("<script type=\"text/javascript\" src=\"" + g_urlJs + "/swfobject/swfobject.js\"></script>");
		}
		
		var player = $("#BugsPlayerController");
		if(player.length < 1) {
			if(!swfobject.hasFlashPlayerVersion("10")) {
				var html = "<p>벅스 플레이어는 Adobe Flash Player 10<br/> 이상을 설치하셔야 사용 가능합니다.<br />" + 
					"<span><a href=\"http://www.adobe.com/go/getflashplayer\" onclick=\"return bugs.utils.openWindow(this);\">Flash 플레이어 받기</a></span></p>" +
					"<div class=\"btnArea\"><span class=\"button typeME\"><a href=\"#\" type=\"cancel\">닫기</a></span></div>";
				
				var popup = new bugs.ui.popup(html, {
					css : "layerDownDRM", 
					title : bugs.ui.TITLE_LOGO
				});
				popup.show();
				return;
			}
			
			// firefox에서는 일단 화면에 플래쉬가 보여야 ExternalInterface.addCallback()이 되기 때문에
			// 일단 화면에 보이게끔 scrollTop으로 container를 생성함
			var top = $(document).scrollTop();
			$("<div><div id=\"BugsPlayerController\"></div></div>").css({position : "absolute", top : top, left : 0, width : 10, height : 10}).appendTo("body");
			
			var flashvars = {};
			if(trackId) flashvars.trackId = trackId;
			if(mvId) flashvars.mvId = mvId;
			if(playForce) flashvars.playForce = playForce;
			
			var params = {
				wmode : "transparent",
				allowScriptAccess : "always" 
			};
			
			var attr = {
				id : "BugsPlayerController"
			};
			
			swfobject.embedSWF(g_urlSwf + "/BugsPlayerController.swf", "BugsPlayerController", "100%", "100%", "10.0.0", "expressInstall.swf", flashvars, params, attr);
		}
		else {
			player = player[0];
			if(trackId && typeof(player.addTrack) == "function") player.addTrack(trackId, playForce);
			if(mvId && typeof(player.addMusicVideo) == "function") player.addMusicVideo(mvId, playForce);
		}		
	},
	handleEvent : function(event, data) {
		switch(event) {
			case "openPlayer" :
				if(data == "Player") {
					window.open(g_urlMusic + "/player", "_blank", "width=430,height=656,resizable=0");	
				}
				else {
					window.open(g_urlMusic + "/mvPlayer", "_blank", "width=970,height=668,resizable=0");
				}
				break;
		}
	},
	download : function(trackId,mvAdultYn) {
		if(!g_isLogged) {
			bugs.ui.showLoginLayer();
			return;
		} else if (mvAdultYn=='Y' && adult_age < 19 ){
			bugs.ui.alertAdultNotice();
			return;
		}		
		
		var buyTp = arguments[1] || "mp3"; // mp3 or mv
		var recommend = arguments[2];
		var type = arguments[3]; // MUSICPD
		if(typeof trackId == "undefined") return;
		if(typeof trackId == "string" || typeof trackId == "number") {
//			정기점검시 적용
/*			alert("보다 안정적인 서비스를 제공해 드리기 위해 서비스 정기 점검을 진행 중입니다.\n" +
					"정기점검으로 인하여 다운로드 서비스 이용이 일시 중단되오니 이용에 차질 없으시기 바랍니다.\n" +
					"이용에 불편을 드린 점 진심으로 사과 드리며,\n" +
					"공지 드린 시간 안에 점검을 마칠 수 있도록 최선을 다하겠습니다.\n\n" +
					"점검일자 : 2010. 08. 24(화)\n" +
					"점검시간 : 오전 05:00 ~ 09:00\n" +
					"점검사유 : 다운로드 서비스 점검");
*/
			if(!recommend){
				window.open(g_urlBilling + "/pay/down/getBillDownLoad?buyTp=" + buyTp + "&downId=" + trackId,"pgPop","width=750px,height=604px;");
			}else if(type == 'MUSICPD'){
				window.open(g_urlBilling + "/pay/down/getBillDownLoad?buyTp=" + buyTp + "&downId=" + trackId + "&esAlbumId=" + recommend,"pgPop","width=750px,height=604px;");
			}
			else{
				window.open(g_urlBilling + "/pay/down/getBillDownLoad?buyTp=" + buyTp + "&downId=" + trackId + "&wrTrack=" + recommend + "&mvType=" + type + "&inType=WR","pgPop","width=750px,height=604px;");
			}
			return;
		} else if(typeof trackId == "object") {
			var trackIdStr = "";
			if(trackId.length == 0) return;
			trackId.each(function(){
				if(trackIdStr != "") trackIdStr = trackIdStr + "," + this.value;
				else trackIdStr = this.value;
			});
//				정기점검시 적용
/*				alert(" 보다 안정적인 서비스를 제공해 드리기 위해 서비스 정기 점검을 진행 중입니다.\n" +
					"정기점검으로 인하여 다운로드 서비스 이용이 일시 중단되오니 이용에 차질 없으시기 바랍니다.\n" +
					"이용에 불편을 드린 점 진심으로 사과 드리며,\n" +
					"공지 드린 시간 안에 점검을 마칠 수 있도록 최선을 다하겠습니다.\n\n" +
					"점검일자 : 2010. 08. 24(화)\n" +
					"점검시간 : 오전 05:00 ~ 09:00\n" +
					"점검사유 : 다운로드 서비스 점검");
*/
			if(type == 'MUSICPD'){
				window.open(g_urlBilling + "/pay/down/getBillDownLoad?buyTp=" + buyTp + "&downId="+trackIdStr + "&esAlbumId=" + recommend,"pgPop","width=750px,height=604px;");
			}else if(typeof type != "undefined"){
				window.open(g_urlBilling + "/pay/down/getBillDownLoad?buyTp=" + buyTp + "&downId="+trackIdStr + "&mvType=" + type,"pgPop","width=750px,height=604px;");
			}else{
				window.open(g_urlBilling + "/pay/down/getBillDownLoad?buyTp=" + buyTp + "&downId="+trackIdStr,"pgPop","width=750px,height=604px;");
			}
			return;
		}
	},
	listenAlbum : function(album_id) {
		if (!album_id) {
			bugs.ui.showAlert("앨범 정보가 없습니다.", {css : "layerAdultNotice"});
			return;
		}
		$.get(
				
				g_urlAjax + "/album/ajax/albumStreamingTracks", 
				{albumId : album_id},
				function(trackIds) {
					if (trackIds) {
						if ($.browser.chrome){
							setTimeout("bugs.music.listen('"+trackIds+"',true)", 200);
							
						}else bugs.music.listen(trackIds,true);
					}
					else {
						bugs.ui.showAlert("음원 권리사의 요청으로<br/>듣기 서비스가 제공되지 않는 앨범입니다.", {css : "layerAdultNotice"});
					}
				}
		);		
	},
	listenEsalbum : function(album_id) {
		if (!album_id) {
			bugs.ui.showAlert("앨범 정보가 없습니다.", {css : "layerAdultNotice"});
			return;
		}
		//alert("listenEsalbum");
		$.post(
				g_urlAjax + "/esalbum/ajax/albumTracks", 
				{albumId : album_id},
				function(trackIds) {
					//alert("trackIds:"+trackIds);
					if (trackIds) {
						bugs.music.listen(trackIds,true);
					}
					else {
						bugs.ui.showAlert("앨범에 곡정보가 없습니다.");
					}
				}
		);		
	},
	
	downloadAlbumCache : function(album_id){
		if (!album_id) {
			bugs.ui.showAlert("앨범 정보가 없습니다.", {css : "layerAdultNotice"});
			return;
		}
		if(!g_isLogged) {
			bugs.ui.showLoginLayer();
			return;
		}
		
		window.open("http://pay.bugs.co.kr/pay/web/buy/album?albumId=" + album_id, "buyAlbumCache", "width=750,height=564");
	},

	downloadAlbum : function(album_id, type) {
		if (!album_id) {
			bugs.ui.showAlert("앨범 정보가 없습니다.", {css : "layerAdultNotice"});
			return;
		}
		if(!g_isLogged) {
			bugs.ui.showLoginLayer();
			return;
		}
		var urlStr = "";
		if(type == "esalbum"){
			urlStr = g_urlAjax + "/esalbum/ajax/albumTracks";
		}else if(type == "playlist"){
			urlStr = g_urlPlaylists+"/ajax/track/string/"+album_id;
		}else{
			urlStr = g_urlAjax + "/album/ajax/albumTracks";
		}
		
		if(type == "playlist"){
			$.getJSON(urlStr, {}, function(data) {
				if (data.total_cnt == 0) {
					bugs.ui.showAlert("앨범에 곡정보가 없습니다.");
				} else {
					bugs.music.download(data.track_str);
				}
				
			});
		}else{
			$.post(
				urlStr, 
				{albumId : album_id},
				function(trackIds) {
					if (trackIds) {
						bugs.music.download(trackIds);
					}
					else {
						bugs.ui.showAlert("앨범에 곡정보가 없습니다.");
					}
				}
			);
		}
	},
	
	_likeOption : function(option) {
		if(typeof option != "undefined" && typeof option.href != "undefined")
			return {anchor : option, success : function(){}, error : function(){} };
		else 
			return bugs.overed( {anchor : null, success : function(){}, error : function(){} },  option || {} );
	},
	_likeActionCb : function(id, action, type, option, toggleFunc, anchor) {
		var panchor = anchor.parent();
		var star = anchor.find("img:first");
		var _src = star.get(0).src;
		
		if(star.length > 0)	 {
			if(action =="add") {
				bugs.utils.imgOver(star.get(0));
				star
				.mouseover(function() { bugs.utils.imgOut(star.get(0)); })
				.mouseout(function() { bugs.utils.imgOver(star.get(0)); });
			} else if(action =="del") {
				bugs.utils.imgOut(star.get(0));
				star
				.mouseout(function() { bugs.utils.imgOut(star.get(0)); })
				.mouseover(function() { bugs.utils.imgOver(star.get(0)); });
			}
		}
		
		if(panchor.hasClass("btnLike")) {
			var btns = anchor.parent().parent().children(".btnLike");
		
			if(btns.siblings('span.bubble').find(".like").length>0) {
				bugs.music._memCount( btns.siblings('span.bubble').find(".like"), id, type);
				
				if(action =="add") {
					anchor.hide();
					anchor.next().show();
				}else if(action =="del") {
					anchor.hide();
					anchor.prev().show();
				}
			} else {
				bugs.music._memCount( btns.siblings('.reputation').find(" dd.like"), id, type);
				
				if(action =="add") {
					btns.first().hide();
					btns.last().show();
				}else if(action =="del") {
					btns.first().show();
					btns.last().hide();
				}
			}
			
			
		} else if(panchor.hasClass("btnArea")) {
			bugs.music._memCount( anchor.parent().prev('.reputation').find(" dd.like"), id, type);
			if(action =="add") {
				anchor.hide();
				anchor.next().show();
			}else if(action =="del") {
				anchor.hide();
				anchor.prev().show();
			}
		} else {
			if(typeof toggleFunc == "function") {
				anchor.get(0).onclick = function() {};
				anchor.unbind("click");
				anchor.bind("click", function() { toggleFunc(id, option); });
			}
		}
		
		if(panchor.hasClass("btn") && panchor.prev('dd.like').length > 0) {
			bugs.music._memCount( panchor.prev('dd.like'), id, type);
			if(action =="add") {
				anchor.hide();
				anchor.next().show();
			}else if(action =="del") {
				anchor.hide();
				anchor.prev().show();
			}
		}
	},
	_likeAction : function(id, action, type, option, toggleFunc) {
		if(typeof id == "undefined") return;
		option = bugs.music._likeOption(option);
		var _act = function() {};
		if(action == "add") {
			_act = likes.add;
		} else if(action == "del") {
			_act = likes.del;
		} else if(action == "adds") {
			_act = likes.adds;
		}
		var idString = "";
		if(typeof id != "string" && typeof id != "number") idString = id.join(",");
		else idString = id;
		
		_act(idString, type, option, function(result) {
			if(option.anchor != null &&  typeof option.anchor != "undefined") {
				if(action == "adds") {
					option.anchor.each(function(idx) {
						var _opt = bugs.clone(option);
						bugs.overed( _opt, {anchor : $(this)} );
						bugs.music._likeActionCb(id[idx], "add", type, _opt, toggleFunc, $(this));
					});
				} else {
					var anchor = $(option.anchor);
					bugs.music._likeActionCb(id, action, type, option, toggleFunc, anchor);
				}
			}
			option.success(id);
		}, function() {
			option.error(id);
		});
	},
	_memCount : function(panel, id, type, callback) {
		if(typeof callback == "undefined") callback = function() {};
		likes.memCount(id, type, function(result) {
			panel.fadeOut(500, function() {panel.text(result).fadeIn(500);});
			callback();
		});
	}, 
	addLikeTrack : function(track_id, option) {
		bugs.music._likeAction(track_id, "add", "TRACK", option, bugs.music.delLikeTrack);
	}, 
	addLikeTracks : function(track_id, option) {
		bugs.music._likeAction(track_id, "adds", "TRACK", option, bugs.music.delLikeTrack);
	}, 
	delLikeTrack : function(track_id, option) {
		bugs.music._likeAction(track_id, "del", "TRACK", option, bugs.music.addLikeTrack);
	},
	addLikeArtist : function(artist_id, option) {
		bugs.music._likeAction(artist_id, "add", "ARTIST", option, bugs.music.delLikeArtist);
	},
	addLikeArtists : function(artist_id, option) {
		bugs.music._likeAction(artist_id, "adds", "ARTIST", option, bugs.music.delLikeArtist);
	},
	delLikeArtist : function(artist_id, option) {
		bugs.music._likeAction(artist_id, "del", "ARTIST", option, bugs.music.addLikeArtist);
	},
	addLikeAlbum : function(album_id, option) {
		bugs.music._likeAction(album_id, "add", "ALBUM", option, bugs.music.delLikeAlbum);
	},
	addLikeAlbums : function(album_id, option) {
		bugs.music._likeAction(album_id, "adds", "ALBUM", option, bugs.music.delLikeAlbum);
	},
	delLikeAlbum : function(album_id, option) {
		bugs.music._likeAction(album_id, "del", "ALBUM", option, bugs.music.addLikeAlbum);
	},
	addLikeMusicVideo : function(album_id, option) {
		bugs.music._likeAction(album_id, "add", "MV", option, bugs.music.delLikeMusicVideo);
	},
	addLikeMusicVideoes : function(album_ids, option) {
		bugs.music._likeAction(album_ids, "adds", "MV", option, bugs.music.delLikeMusicVideo);
	},
	delLikeMusicVideo : function(album_id, option) {
		bugs.music._likeAction(album_id, "del", "MV", option, bugs.music.addLikeMusicVideo);
	},
	setLivebell : function(trackId) {
		bugs.music._cpPopup("livebell", trackId, "ME");
	},
	setLivebellTo : function(trackId) {
		bugs.music._cpPopup("livebell", trackId, "TO");
	},
	setColoring : function(trackId) {
		bugs.music._cpPopup("coloring", trackId, "ME");
	},
	setColoringTo : function(trackId) {
		bugs.music._cpPopup("coloring", trackId, "TO");
	},
	viewMusicVideo : function(mvId, playForce, mvAdultYn) {
		if(typeof mvAdultYn == "undefined") mvAdultYn = 'N';
		if (mvAdultYn=='Y' && !g_isLogged ){ 
			bugs.ui.showLoginLayer();
			return;
		} /*else if (mvAdultYn=='Y' && adult_age < 19 ){
			bugs.ui.alertAdultNotice();
			return;
		}	*/	
			
		if(typeof mvId == "undefined") return;
		if(typeof mvId == "string") {
		} else if(typeof mvId == "object") {
			var mvIdStr = "";
			if(mvId.length == 0) return;
			mvId.each(function() {
				if(mvIdStr != "") mvIdStr = mvIdStr + "," + this.value;
				else mvIdStr = this.value;
			});
			mvId = mvIdStr;
		}
		
		if(!this.flashInstalled) {
			this.flashPopup.show();
			return;
		}
		
		var controller = this.getPlayerController();
		if(!controller) return;
		
		if(controller.isMvPlayerExist()) {
			controller.addMusicVideo(mvId, playForce);
		}
		else {
			window.open(g_urlMusic + "/mvPlayer?mvId=" + mvId, "BugsMvPlayer", "width=970,height=668,resizable=0");
		}
		
		//this._loadController(null, mvId, playForce);
	},
	viewMV : function(mvId, mvAdultYn) {
		if(typeof mvAdultYn == "undefined") mvAdultYn = 'N';
		bugs.music.viewMusicVideo(mvId, true, mvAdultYn);
	},
	addMVList : function(mvId, mvAdultYn) {
		if(typeof mvAdultYn == "undefined") mvAdultYn = 'N';
		bugs.music.viewMusicVideo(mvId, false, mvAdultYn);
	},	
	downloadMusicVideo : function(mvId, quality, mvAdultYn) {
		if(typeof mvAdultYn == "undefined") mvAdultYn = 'N';
		if(typeof quality == "undefined") quality = 'SD';
		bugs.music.download(mvId, "mv",mvAdultYn, quality);
	},
	dnFullMV : function(mvId, mvAdultYn) {		
		if(typeof mvAdultYn == "undefined") mvAdultYn = 'N';
		bugs.music.downloadMusicVideo(mvId, bugs.music.MV_QUALITY_FULLHD,mvAdultYn);
	},
	dnHdMV : function(mvId, mvAdultYn) {
		if(typeof mvAdultYn == "undefined") mvAdultYn = 'N';
		bugs.music.downloadMusicVideo(mvId, bugs.music.MV_QUALITY_HD,mvAdultYn);
	},
	dnSdMV : function(mvId, mvAdultYn) {
		if(typeof mvAdultYn == "undefined") mvAdultYn = 'N';
		bugs.music.downloadMusicVideo(mvId, bugs.music.MV_QUALITY_SD,mvAdultYn);
	},
	dnMp4MV : function(mvId, mvAdultYn) {
		if(typeof mvAdultYn == "undefined") mvAdultYn = 'N';
		bugs.music.downloadMusicVideo(mvId, bugs.music.MV_QUALITY_MP4,mvAdultYn);
	},
	// Cp 구분 열기
	_cpPopup : function() {
		var mType = arguments[0] || '';
		var mList = arguments[1] || '';
		var mMode = arguments[2] || '';

		switch (mType.toLowerCase()) {
			case 'livebell'		:	// 라이브벨
				void(window.open('http://livebell.bugs.co.kr/player/playeruser?track_id='+mList+'&mode='+mMode, 'Livebell', 'width=350,height=495,resizable=no,scrollbars=0'));
				break;
			case 'coloring'		:	// 컬러링
				void(window.open('http://coloring.bugs.co.kr/player/playeruser?track_id='+mList+'&mode='+mMode, 'Coloring', 'width=350,height=473,resizable=no,scrollbars=0'));
				break;
			case 'ring'			:	// 통화연결음
				void(window.open('http://ring.bugs.co.kr/POP4/PopSet.asp?C_IDX='+mList+'&dType=1', 'MusicRing', 'width=250,height=250,resizable=no,scrollbars=0'));
				break;
			case 'ringgift'		:	// 통화연결음 - 선물
				void(window.open('http://ring.bugs.co.kr/POP4/PopSet.asp?C_IDX='+mList+'&dType=2', 'MusicRing', 'width=250,height=250,resizable=no,scrollbars=0'));
				break;
			case 'bell'			:	// 벨소리
				void(window.open('http://bell.bugs.co.kr/popup2/PopupBuy.asp?ptype=listen&mcode='+mList+'&stype=', 'MusicBell', 'width=250,height=250,resizable=no,scrollbars=0'));
				break;
			case 'bellgift'		:	// 벨소리 - 선물
				void(window.open('http://bell.bugs.co.kr/popup2/PopupBuy.asp?ptype=gift&mcode='+mList+'&stype=', 'MusicBell', 'width=250,height=250,resizable=no,scrollbars=0'));
				break;
			case 'cdmall'		:	// 음반몰
				void(window.open('http://cdmall.bugs.co.kr/shop/mall_pcode.php?gcode='+mList, 'CDMall'));
				break;
		}
	}, moreView : function(descObj, height){
		var _desc = $("p, .bioCont", descObj);
		var _height = _desc.height();
		if(typeof _height == "number" && _height <= height) {
			$(".more", descObj).hide();
		} else {
			_desc.height(height);
			$(".more", descObj).show();
		}
	}

}



bugs.music.albumList = bugs.create();
bugs.music.albumList.prototype = {
	initialize : function(id, type, page, row, total, sort) {
		this.id = id;
		this.type = type;
		this.page =eval(page);
		this.row = eval(row);
		this.total = eval(total);
		this.sort = sort;
		this.name = type + id;
		this.box = $("#id" + this.name);
		this.boxList = $("#idList" + this.name)
	},
	initCheckBox : function() {
		if(typeof this.name != 'string') return;
		var arrChecked = [];
		
		$("#id" + this.name + " > ul .listRow").each(function() {
			var li = $(this);
			var _cc = new bugs.form.checkbox(li.find("div.check"), "_chk"+name, {
				checked : function() {
					li.addClass("rowSelect");
				},
				unchecked : function() {
					li.removeClass("rowSelect");
				}
			});
			if(typeof _cc != "undefined" && _cc.isDisabled() == false) {
				arrChecked.push(_cc);
			}
		});
		
		this.cbox = new bugs.form.checkbox($("#id" + this.name + " .oneclickAction div.check"), "_checkAll"+this.name, {
			checked : $.proxy( function() {
				for(var i=0;i<this.trackChecked.length;i++) {
					this.trackChecked[i].checked();
				}
			}, this),
			unchecked : $.proxy( function() {
				for(var i=0;i<this.trackChecked.length;i++) {
					this.trackChecked[i].unchecked();
				}
			}, this)
		});
		
		this.trackChecked = arrChecked;
	},
	more : function() {
		if(this.row *  eval(this.page) > this.total) return;
		
		var _page = eval(this.page) + 1;
		var url = g_urlMusic + "/album/ajax/list";
		var data = {type : this.type, id : this.id, decorator : "blank"};
		if(typeof this.page != "undefined") data.page = _page;
		if(typeof this.row != "undefined") data.row = this.row;
		if(typeof this.sort != "undefined") data.sort = this.sort;
		$.get(url, data, $.proxy(function(result) {
			this.boxList.append(result);
			this.page = _page;
			if(this.row * _page > this.total) this.boxList.next('.moreList').hide();
		}, this), "html");
	},
	chkCheckBox : function(btn) {
		var chks = $("ul li input:checkbox:checked", this.box);
		if(chks.length == 0) {
			this.alert(btn);
			//bugs.ui.showAlert("선택한 곡이 없습니다.", {});
			return false;
		} else return chks;
		
	},	
	_getAlbumTitleTrackIds : function(albumId) {
		var albumIdStr = "";
		if(albumId.length == 0) {
			bugs.ui.showAlert("앨범을 선택하여 주십시오.", {css : "layerAdultNotice"});
			return;
		}
		for(var i=0;i < albumId.length;i++) {
			albumIdStr += $(albumId[i]).val();
			if(i < albumId.length - 1) albumIdStr +=",";
		}
		return albumIdStr;
	},
	addToMyAlbum : function(btn) {
		if(!g_isLogged) {
			bugs.ui.showLoginLayer();
			return;
		}
		else if(chks = this.chkCheckBox(btn))
		{	
			var albumIdStr = this._getAlbumTitleTrackIds(chks);
			if (!albumIdStr) {
				bugs.ui.showAlert("앨범을 선택하여 주십시오.", {css : "layerAdultNotice"});
				return;
			}
			$.post(
					g_urlMusic + "/album/ajax/albumTitle", 
					{albumIds : albumIdStr},
					function(trackIds) {
						if (trackIds) {
							playlists.showPlaylistLayer($(btn), trackIds);
						}
						else {
							bugs.ui.showAlert("앨범의 대표 타이틀 정보가 없습니다.");
						}
					}
			);
			
		}
	}, 
	listenAlbumTitleAll : function(btn) {
		this.cbox.checked();
		
		var listenForce = arguments[1];if(listenForce==null)listenForce=true;
		
		if(chks = $("ul li input:checkbox", this.box)) {
			var albumIdStr = this._getAlbumTitleTrackIds(chks);
			if (!albumIdStr) {
				bugs.ui.showAlert("앨범을 선택하여 주십시오.", {css : "layerAdultNotice"});
				return;
			}
			$.post(
					g_urlMusic + "/album/ajax/albumTitle", 
					{albumIds : albumIdStr},
					function(trackIds) {
						if (trackIds) {
							bugs.music.listen(trackIds,listenForce);
						}
						else {
							bugs.ui.showAlert("앨범의 대표 타이틀 정보가 없습니다.");
						}
					}
			);
		}
	},	
	listenAlbumTitle : function(btn) {
		var listenForce = arguments[1];if(listenForce==null)listenForce=true;
		if(chks = this.chkCheckBox(btn)) {
			var albumIdStr = this._getAlbumTitleTrackIds(chks);
			if (!albumIdStr) {
				bugs.ui.showAlert("앨범을 선택하여 주십시오.", {css : "layerAdultNotice"});
				return;
			}
			$.post(
					g_urlMusic + "/album/ajax/albumTitle", 
					{albumIds : albumIdStr},
					function(trackIds) {
						if (trackIds) {
							bugs.music.listen(trackIds, listenForce);
						}
						else {
							bugs.ui.showAlert("앨범의 대표 타이틀 정보가 없습니다.");
						}
					}
			);
		}
	},
	downloadAlbumTitle : function(btn) {
		if(!g_isLogged) {
			bugs.ui.showLoginLayer();
			return;
		}

		if(chks = this.chkCheckBox(btn)) {
			var albumIdStr = this._getAlbumTitleTrackIds(chks);
			if (!albumIdStr) {
				bugs.ui.showAlert("앨범을 선택하여 주십시오.", {css : "layerAdultNotice"});
				return;
			}
			$.post(
					g_urlMusic + "/album/ajax/albumTitle", 
					{albumIds : albumIdStr},
					function(trackIds) {
						if (trackIds) {
							bugs.music.download(trackIds);
						}
						else {
							bugs.ui.showAlert("앨범의 대표 타이틀 정보가 없습니다.");
						}
					}
			);
		}
	},
	likesAlbumTitle : function(btn) {
		if(chks = this.chkCheckBox(btn)) {
			var albumIdStr = this._getAlbumTitleTrackIds(chks);
			if (!albumIdStr) {
				bugs.ui.showAlert("앨범을 선택하여 주십시오.", {css : "layerAdultNotice"});
				return;
			}
			$.post(
					g_urlMusic + "/album/ajax/albumTitle", 
					{albumIds : albumIdStr},
					function(trackIds) {
						if (trackIds) {
							likes.adds(trackIds, 'TRACK', function() {}, function() {});
						}
						else {
							bugs.ui.showAlert("앨범의 대표 타이틀 정보가 없습니다.");
						}
					}
			);
		}
	},	
	alert : function(btn) {
		var html = '<p class="layerInfoMsg inform" style="display:none;">&nbsp;<span>앨범을 먼저 선택해 주세요.</span></p>';
		var oBtn = $(btn);
		var _offset = oBtn.offset();
		var plusTop = navigator.appName.match(/Explorer/i) ? 0 : 9;
		var alertLayer = $(html).appendTo("body").css({
			"top" : (_offset.top+oBtn.height()+plusTop)+"px",
			"left" : _offset.left+"px",
			width : 142
		}).fadeIn(500).delay(1500).fadeOut(500);
		
	}	
}

bugs.music.topSpotList = {
	page : 1,
	totalPage : null,
	elemItems : "#topSpotList > ul",
	
	getTotalPage : function() {
		if (this.totalPage == null) {
			this.totalPage = $(this.elemItems).length || 1;
		}
		return this.totalPage;
	},
	
	prev : function() {
		this.page = (this.page <= 1) ? this.getTotalPage() : this.page-1;
		this.show();
	},
	
	next : function() {
		this.page = (this.page >= this.getTotalPage()) ? 1 : this.page+1;
		this.show();
	},
	
	show : function() {
		$(this.elemItems).hide();
		$(this.elemItems).eq(this.page-1).show();
	}
}

bugs.music.trackList = bugs.create();
bugs.music.trackList.prototype = {
	trackChecked : [],
	initialize : function(id, type, page, row, total, sort, check, albumDnlOnly) {
		this.id = id;
		this.type = type;
		this.page =eval(page);
		this.row = eval(row);
		this.total = eval(total);
		this.sort = sort;
		this.check = check;
		this.albumDnlOnly = albumDnlOnly;
		this.name = type + id;
		this.box = $("#id" + this.name);
	},
	initCheckBox2 : function() {
		if(typeof this.name != 'string') return;
		var arrChecked = [];
		
		$("#id" + this.name + " > ul .listRow").each(function() {
			var li = $(this);
			var _cc = new bugs.form.checkbox(li.find("div.check"), "_chk"+name, {
				checked : function() {
					li.addClass("rowSelect");
				},
				unchecked : function() {
					li.removeClass("rowSelect");
				}
			});
			if(typeof _cc != "undefined" && _cc.isDisabled() == false) {
				arrChecked.push(_cc);
			}
		});
		
		this.cbox = new bugs.form.checkbox($("#id" + this.name + " > div.listBtns > div.check"), "_checkAll"+this.name, {
			checked : $.proxy( function() {
				for(var i=0;i<this.trackChecked.length;i++) {
					this.trackChecked[i].checked();
				}
			}, this),
			unchecked : $.proxy( function() {
				for(var i=0;i<this.trackChecked.length;i++) {
					this.trackChecked[i].unchecked();
				}
			}, this)
		});
		
		this.trackChecked = arrChecked;
	},
	initCheckBox : function() {
		if(typeof this.name != 'string') return;
		var arrChecked = [];
		
		$("#id" + this.name + " > ul .listRow").each(function() {
			var li = $(this);
			var _cc = new bugs.form.checkbox(li.find("div.check"), "_chk"+name, {
				checked : function() {
					li.addClass("rowSelect");
				},
				unchecked : function() {
					li.removeClass("rowSelect");
				}
			});
			if(typeof _cc != "undefined" && _cc.isDisabled() == false) {
				arrChecked.push(_cc);
			}
		});
		
		this.cbox = new bugs.form.checkbox($("#id" + this.name + " .oneclickAction div.check"), "_checkAll"+this.name, {
			checked : $.proxy( function() {
				for(var i=0;i<this.trackChecked.length;i++) {
					this.trackChecked[i].checked();
				}
			}, this),
			unchecked : $.proxy( function() {
				for(var i=0;i<this.trackChecked.length;i++) {
					this.trackChecked[i].unchecked();
				}
			}, this)
		});
		
		this.trackChecked = arrChecked;
	},
	more : function() {
		if(this.row * eval(this.page) > this.total) return;
		
		var _page = eval(this.page) + 1;
		var url = g_urlMusic + "/track/ajax/list/";
		var data = {decorator : "blank", id : this.id, type : this.type};
		if(typeof this.page != "undefined") data.page = _page;
		if(typeof this.row != "undefined") data.row = this.row;
		if(typeof this.sort != "undefined") data.sort = this.sort;
		if(typeof this.check != "undefined") data.check = this.check;
	
		$.get(url, data, $.proxy(function(result) {
			var objResult = $(result);
			if(!objResult.hasClass("listRow")) return;
			
			if (this.type == "ARTIST") this.box.find("ul.list.trackSimpleList").append(result);
			else this.box.find("ul.list.trackList").append(result);
			
			this.page = _page;
			if(this.row * _page >= this.total) this.box.find('.moreList').hide();
			
			this.initCheckBox();
			
		},this), "html");
	}, 
	chkCheckBox : function(btn) {
		var chks = $("ul li input:checkbox:checked", this.box).not("input:disabled");
		return this.__chkCheckBox(btn, chks);
	},
	chkStreamCheckBox : function(btn) {
		/*
		if($("input:hidden[name=_isStream]:not(:disabled)", this.box).length == 0) {
			bugs.ui.showAlert("재생 가능한 곡이 없습니다.", {css : "layerLoginMsg"});
			return;
		}
		*/
		var disabledList = $("ul li:has(input:hidden[name=_isStream]:disabled) input:checkbox:checked:not(:disabled)", this.box);
		if(disabledList.length > 0) {
			var _html = '<div class="putFailure">' +
				'<p>선택하신 곡 중 <em>'+disabledList.length+'</em>곡의 음원은<br />권리사의 요청으로 들으실 수 없습니다.</p>'+
				'<span class="button typeME"><a href="javascript:void(0);">확인</a></span>' +
				'</div>';
			this.showPopup(_html, {
				title : bugs.ui.TITLE_LOGO,css : "layerPutSong", onInit : $.proxy(function(popup) {
					popup.layer.find(".button.typeME a").click($.proxy(function() {
						popup.hide();
						if($("ul li input:checkbox:checked", this.box).length > disabledList.length) {
							var chks = this.chkStreamCheckBoxAndPlay(btn);
							if(chks)
								bugs.music.listen(chks);
						}
					}, this));
				}, this)
			});
			return;
		}
		
		return this.chkStreamCheckBoxAndPlay(btn);
	},
	chkStreamCheckBoxAndPlay : function(btn) {
		
		var chks = $("ul li:has(input:hidden[name=_isStream]:not(:disabled)) input:checkbox:checked:not(:disabled)", this.box);
		//alert(chks);
		return this.__chkCheckBox(btn, chks);
	},
	chkDnlCheckBox : function(btn) {
		/*
		if($("input:hidden[name=_isDown]:not(:disabled)", this.box).length == 0) {
			bugs.ui.showAlert("다운로드 가능한 곡이 없습니다.", {css : "layerLoginMsg"});
			return;
		}
		*/
		
		var disabledList = $("ul li:has(input:hidden[name=_isDown]:disabled) input:checkbox:checked:not(:disabled)", this.box);
		if(disabledList.length > 0) {
			if(this.albumDnlOnly){
				var _html = '<div class="putFailure">' +
				'<p>앨범전체 구매만 가능한 앨범 입니다.<br />상단의 <em>앨범다운</em>버튼을<br>클릭하시기 바랍니다.</p>'+
				'<span class="button typeME"><a href="javascript:void(0);">확인</a></span>' +
				'</div>';
			}else{
				var _html = '<div class="putFailure">' +
				'<p>선택하신 곡 중 <em>'+disabledList.length+'</em>곡의 음원은<br>권리사의 요청으로 다운로드 하실 수 없습니다.</p>'+
				'<span class="button typeME"><a href="javascript:void(0);">확인</a></span>' +
				'</div>';
			}
			
			
			this.showPopup(_html, {
				title : bugs.ui.TITLE_LOGO,css : "layerPutSong downTypeC", onInit : $.proxy(function(popup) {
					popup.layer.find(".button.typeME a").click($.proxy(function() {
						popup.hide();
						if($("ul li input:checkbox:checked", this.box).length > disabledList.length) {
							var chks = this.chkDnlCheckBoxAndPlay(btn);
							if(chks)
								bugs.music.download(chks);
						}
					}, this));
				}, this)
			});
			return;
		}
		
		
		
		
		
		//var chks = $("ul li input:hidden[name=_isDown]", this.box).not("input:disabled");
		return this.chkDnlCheckBoxAndPlay(btn);
	},
	chkDnlCheckBoxAndPlay : function(btn) {
		var chks = $("ul li:has(input:hidden[name=_isDown]:not(:disabled)) input:checkbox:checked:not(:disabled)", this.box);
		return this.__chkCheckBox(btn, chks);
	},
	__chkCheckBox : function(btn, chks) {
		if(chks.length == 0) {
			this.alert(btn);
			return false;
		} else return chks;
		
	},
	listen : function(btn) {
		var listenForce = arguments[1];if(listenForce==null)listenForce=true;
		if(chks = this.chkStreamCheckBox(btn))
			bugs.music.listen(chks,listenForce);
	}, 
	addToMyAlbum : function(btn) {
		if(!g_isLogged) {
			bugs.ui.showLoginLayer();
			return;
		}
		else if(chks = this.chkCheckBox(btn))
		{
			playlists.showPlaylistLayer($(btn), chks);
		}
	}, 
	listenAll : function(btn) {
		var listenForce = arguments[1];if(listenForce==null)listenForce=true;
		var aList = $("input:hidden[name=_isStream]:not(:disabled)", this.box);
		if(aList.length == 0) {
			bugs.ui.showAlert("재생 가능한 곡이 없습니다.", {css : "layerLoginMsg"});
			return;
		}
		
		
		$("#_checkAll"+this.name).attr("checked",true).parent().parent().addClass("click");
		
		$(this.trackChecked).each(function() {
			var _this  = this;
			aList.each(function() {
				if(this.value == _this.val()) _this.checked(); 
			});
			
		});
		//this.cbox.checked();
		
		var chks = $("ul li input:hidden[name=_isStream]", this.box).not("input:disabled");
		bugs.music.listen(chks, listenForce);
	}, 
	download : function(btn) {
		if(chks = this.chkDnlCheckBox(btn)){
			var recommend = arguments[1];
			var type = arguments[2];
			
			if(type == 'MUSICPD'){
				bugs.music.download(chks,'',recommend,type);
			}
			else{
				bugs.music.download(chks);
			}
		}
	},
	likes : function(btn) {
		if(chks = this.chkCheckBox(btn))
			bugs.likes.track(chks);
	},
	adds : function(btn) {
		if(chks = this.chkCheckBox(btn)) {
			var ids = [];
			chks.each(function() {
				ids.push(this.value);
			});
			bugs.music.addLikeTracks(ids, {
				anchor : $("ul li:has(input:checkbox:checked) .btnAction a:odd", this.box),
				success : $.proxy(function() {
					for(var i=0;i<this.trackChecked.length;i++) {
						this.trackChecked[i].unchecked();
					}
				}, this)
			});
		}
	}, 
	alert : function(btn, msg) {
		if(typeof msg == "undefined") msg = "곡을 먼저 선택해 주세요.";
		var html = '<p class="layerInfoMsg inform" style="display:none;">&nbsp;<span>' + msg + '</span></p>';
		var oBtn = $(btn);
		var _offset = oBtn.offset();
		var plusTop = navigator.appName.match(/Explorer/i) ? 0 : 9;
		var alertLayer = $(html).appendTo("body").css({
			"top" : (_offset.top+oBtn.height()+plusTop)+"px",
			"left" : _offset.left+"px",
			width : 142
		}).fadeIn(500).delay(1500).fadeOut(500);
		
	}, 
	showPopup : function(msg, option) {
		if(this._popup && this._popup != null) {
			this._popup.remove();
			this._popup = null;
		}
		this._popup = new bugs.ui.popup(msg, option);
		this._popup.show();
	},
	downloadAll : function(btn) {
		var aList = $("input:hidden[name=_isDown]:not(:disabled)", this.box);
		var recommend = arguments[1];
		var type = arguments[2];		
		if(aList.length == 0) {
			bugs.ui.showAlert("다운로드 가능한 곡이 없습니다.", {css : "layerLoginMsg"});
			return;
		}
		
		$(this.trackChecked).each(function() {
			var _this  = this;
			aList.each(function() {
				if(this.value == _this.val()) _this.checked(); 
			});
			
		});

		if(chks = this.chkDnlCheckBox(btn)){
			if(type == 'MUSICPD') bugs.music.download(chks, '', recommend, type);
			else bugs.music.download(chks);
		}
	}

}



bugs.music.musicvideoList = bugs.create();
bugs.music.musicvideoList.prototype = {
		trackChecked : [],
	initialize : function(id, type, page, row, total, check) {
		this.id = id;
		this.type = type;
		this.page =eval(page);
		this.row = eval(row);
		this.total = eval(total);
		this.check = check;
		
		this.name = type + id;
		this.box = $("#id" + this.name);
	},
	initCheckBox2 : function() {
		if(typeof this.name != 'string') return;
		var arrChecked = [];
		
		$("#id" + this.name + " > ul .listRow").each(function() {
			var li = $(this);
			var lichk = li.find("input:checkbox[name^='_chk']");
			var _cc =  new bugs.form.checkbox(li.find("div.check"), "_chk"+name, {
				checked : function() {
					li.addClass("rowSelect");
					
					// 19금일 경우 선택 못하도록 
					//if (g_isLogged == false || (g_isLogged==true && ))
					/*
					if (typeof lichk == 'object' && lichk.attr("is19") == "Y") { // 19금
						li.removeClass("rowSelect");
						lichk.attr('checked', false);
					}*/
				},
				unchecked : function() {
					li.removeClass("rowSelect");
				}
			});
			if(typeof _cc != "undefined" && _cc.isDisabled() == false) {
				arrChecked.push(_cc);
			}

		});
		this.cbox = new bugs.form.checkbox($("#id" + this.name + " > div.listBtns > div.check"), "_checkAll"+this.name, {
			checked : $.proxy( function() {
				for(var i=0;i<this.trackChecked.length;i++) {
					this.trackChecked[i].checked();
				}
			}, this),
			unchecked : $.proxy( function() {
				for(var i=0;i<this.trackChecked.length;i++) {
					this.trackChecked[i].unchecked();
				}
			}, this)
		});
		this.trackChecked = arrChecked;
	},
	initCheckBox : function() {
		if(typeof this.name != 'string') return;
		var arrChecked = [];
		
		$("#id" + this.name + " > ul .listRow").each(function() {
			var li = $(this);
			var lichk = li.find("input:checkbox[name^='_chk']");
			var _cc =  new bugs.form.checkbox(li.find("div.check"), "_chk"+name, {
				checked : function() {
					li.addClass("rowSelect");
					
					// 19금일 경우 선택 못하도록 
					//if (g_isLogged == false || (g_isLogged==true && ))
					/*
					if (typeof lichk == 'object' && lichk.attr("is19") == "Y") { // 19금
						li.removeClass("rowSelect");
						lichk.attr('checked', false);
					}*/
				},
				unchecked : function() {
					li.removeClass("rowSelect");
				}
			});
			if(typeof _cc != "undefined" && _cc.isDisabled() == false) {
				arrChecked.push(_cc);
			}

		});
		this.cbox = new bugs.form.checkbox($("#id" + this.name + " .oneclickAction div.check"), "_checkAll"+this.name, {
			checked : $.proxy( function() {
				for(var i=0;i<this.trackChecked.length;i++) {
					this.trackChecked[i].checked();
				}
			}, this),
			unchecked : $.proxy( function() {
				for(var i=0;i<this.trackChecked.length;i++) {
					this.trackChecked[i].unchecked();
				}
			}, this)
		});
		this.trackChecked = arrChecked;
	},
	more : function() {
		if(this.row * eval(this.page) > this.total) return;
		
		var _page = eval(this.page) + 1;
		var url = g_urlMusic + "/mv/ajax/list/";
		var data = {decorator : "blank", id : this.id, type : this.type};
		if(typeof this.page != "undefined") data.page = _page;
		if(typeof this.row != "undefined") data.row = this.row;
		if(typeof this.check != "undefined") data.check = this.check;
		$.get(url, data, function(result) {
			this.box.find("ul.list.musicvideoList").append(result);
			this.page = _page;
			if(this.row * _page >= this.total) this.box.find('.moreList').hide();
			this.initCheckBox();
			
		}.bind(this), "html");
	}, 
	/*
	chkCheckBox : function(btn) {
		var chks = $("ul li input:checkbox:checked", this.box);
		if(chks.length == 0) {
			this.alert(btn);
			//bugs.ui.showAlert("선택한 뮤직비디오가 없습니다.", {});
			return false;
		} else return chks;
		
	},
	*/
	chkCheckBox : function(btn) {
		var chks = $("ul li input:checkbox:checked", this.box).not("input:disabled");
		return this.__chkCheckBox(btn, chks);
	},
	chkStreamCheckBox : function(btn) {
		if($("input:hidden[name=_isStream]:not(:disabled)", this.box).length == 0) {
			bugs.ui.showAlert("재생 가능한 뮤직비디오가 없습니다.", {css : "layerLoginMsg"});
			return;
		}
		//var chks = $("ul li input:hidden[name=_isStream]", this.box).not("input:disabled");
		var chks = $("ul li:has(input:hidden[name=_isStream]:not(:disabled)) input:checkbox:checked:not(:disabled)", this.box);
		return this.__chkCheckBox(btn, chks);
	},
	chkDnlCheckBox : function(btn) {
		if($("input:hidden[name=_isDown]:not(:disabled)", this.box).length == 0) {
			bugs.ui.showAlert("다운로드 가능한 뮤직비디오가 없습니다.", {css : "layerLoginMsg"});
			return;
		}
		//var chks = $("ul li input:hidden[name=_isDown]", this.box).not("input:disabled");
		var chks = $("ul li:has(input:hidden[name=_isDown]:not(:disabled)) input:checkbox:checked:not(:disabled)", this.box);
		return this.__chkCheckBox(btn, chks);
	},
	__chkCheckBox : function(btn, chks) {
		if(chks.length == 0) {
			this.alert(btn);
			return false;
		} else return chks;
		
	},
		
	view : function(btn) {
		if(chks = this.chkStreamCheckBox(btn))
			bugs.music.viewMusicVideo(chks);
	},
	viewAll : function(btn) {
		var aList = $("input:hidden[name=_isStream]:not(:disabled)", this.box);
		if(aList.length == 0) {
			bugs.ui.showAlert("재생 가능한 뮤직비디오가 없습니다.", {css : "layerLoginMsg"});
			return;
		}
		
		$("#_checkAll"+this.name).attr("checked",true).parent().parent().addClass("click");

		$(this.trackChecked).each(function() {
			var _this  = this;
			aList.each(function() {
				if(this.value == _this.val()) _this.checked(); 
			});
			
		});
		var chks = $("ul li input:hidden[name=_isStream]", this.box).not("input:disabled");
		bugs.music.viewMusicVideo(chks);
		
		//this.cbox.checked();
		//var chks = $("ul li input:checkbox", this.box);
		//bugs.music.viewMusicVideo(chks);
	}, 
	download : function(btn) {
		if(chks = this.chkDnlCheckBox(btn))
			bugs.music.downloadMusicVideo(chks);
	},
	adds : function(btn) {
		if(chks = this.chkCheckBox(btn)) {
			var ids = [];
			chks.each(function() {
				ids.push(this.value);
			});
			bugs.music.addLikeMusicVideoes(ids, {
				anchor : $("ul li:has(input:checkbox:checked) .btnAction a", this.box),
				/*success : function() {
					for(var i=0;i<this.trackChecked.length;i++) {
						this.trackChecked[i].unchecked();
					}
				}*/
				/*스크립트 에러 수정 */
				success : $.proxy(function() {
					for(var i=0;i<this.trackChecked.length;i++) {
						this.trackChecked[i].unchecked();
					}
				}, this)
			});
		}
	}, 
	alert : function(btn) {
		var html = '<p class="layerInfoMsg inform" style="display: none;"><span>뮤비를 먼저 선택해 주세요.</span></p>';
		var oBtn = $(btn);
		var _offset = oBtn.offset();
		var plusTop = navigator.appName.match(/Explorer/i) ? 0 : 9;
		var alertLayer = $(html).appendTo("body").css({
			"top" : (_offset.top+oBtn.height()+plusTop)+"px",
			"left" : _offset.left+"px",
			width : 152,
			"background-position": "0 -150px"
		}).fadeIn(500).delay(1500).fadeOut(500);
		
	}
}


bugs.music.photoLayer = bugs.create(); 
bugs.music.photoLayer.prototype = {
	maxImgSize : {width : 446, height : 296},
	ROW_NUM : 9,
	initialize : function(url, data) {
		this.url = url;
		this.data = data;
		this.page = 1;
		this.row = this.ROW_NUM;
		if(typeof data.id != "undefined") this.id = data.id;
		
	},
	TEMPLATE : '<div class="layerPopup layerGallery" style="left:50%;top:186px;margin-left:-310px;">' +
		'<h1>이미지 갤러리</h1>' +
		'<div class="content">' +
		'	<div class="pagination">' +
		'		<strong><%=obj.page%></strong><span> / <%=obj.pageCount%></span>' +
		'		<a href="" title="원본보기" class="viewAll" target="_blank">원본보기</a>' +
		'	</div>' +
		'	<div class="imgScreen">' +
		'		<a href="" target="_blank"><img style="display:none;" alt=""/></a>' +
		'	</div>' +
		'	<div class="photoList">' +
		'		<span class="btn bcPrev"><a href="javascript:void(0);">이전</a></span>' +
		'		<span class="btn bcNext"><a href="javascript:void(0);">다음</a></span>' +
		'		<ul>' +
		'			<%for(var i=0;i<9;i++) { %><li></li><% } %>' +
		'		</ul>' +
		'	</div>' +
		'	<div class="btnArea"><span class="button typeL"><a href="javascript:void(0);">닫기</a></span></div>' +
		'	<div class="btnClose"><a href="javascript:void(0);"><span>닫기</span></a></div>' +
		'</div>' +
		'</div>',
	open : function() {
		if($(".layerPopup.layerGallery").length > 0) return;
		
		var templateHtml = this.TEMPLATE;
		$.ajax({
			url : this.url,
			data : this.data,
			success : $.proxy(function(result) {
				this.result = result;
				var selectedIdx = 0;
				
				this.pageCount = bugs.math.ceil(result.length / this.row, 0);
				var _tmp = new bugs.template(templateHtml, {
					page : this.page,
					pageCount : this.pageCount,  
					list : result
				});
				
				this.layer = $(_tmp.html()).appendTo("body");
				
				this.loadingLayer = new bugs.ui.loadingLayer("이미지 로딩 중입니다.");
				
				//if($.browser.msie && $.browser.version < 7) {
					this.layer.css(
							{position : "absolute", left : "50%", top : 186, "margin-left" : -310}
					);
				//} else {
				//	this.layer.css(
				//			{position : "fixed", left : "50%", top : 130, "margin-left" : -310}
				//	);
				//}
				this.layer.find(".btnArea .button a, .btnClose a").click(
						$.proxy(function() { this.close(); }, this)
				);
				
				
				
				// 하단 list
				this.listImg();
				
				this.layer.find(".photoList .bcPrev a").click($.proxy(this.prevPage, this));
				this.layer.find(".photoList .bcNext a").click($.proxy(this.nextPage, this));
				
				//
				
			}, this),
			dataType : "json"
		});
		
	},
	getSelectedImg : function() {
		var selected;
		if(typeof this.id == "undefined" || this.id == null) {
			
			selected = this.result[(this.page - 1)*this.row];
		} else {
			for(var i=0;i<this.result.length;i++) {
				if(this.result[i].id == this.id) {
					selectedIdx = i;
					this.page = bugs.math.ceil((selectedIdx+1)/this.row);
					this.id =null;
					selected = this.result[i];
				}
			}
		}
		if(typeof selected == "undefined") selected = this.result[0];
		return selected;

	},
	listImg : function() {
		
		this.displayImg(this.getSelectedImg());
		this.layer.find(".pagination strong").text(this.page);

		this.layer.find(".photoList ul li a").remove();
		var _this = this;
		this.layer.find(".photoList ul li").each(function(idx) {
			var listIdx = idx + (_this.page-1)*_this.row;
			if(listIdx < _this.result.length) {
				$(this).click($.proxy(function(event) {
					event.preventDefault();
					this.selectImg(listIdx);
				}, _this)).append('<a href="javascript:void(0);"><img src="'+_this.result[listIdx].clip59+'" onerror="bugs.utils.imgError(this);" alt="" /><span class="thumbnailValign"></span><span class="over"></span></a>');
			}
		});
		
		this.layer.find(".photoList ul li a img").each(
			function() {
				var w = Math.floor(Math.random()*300);
				$(this).delay(300 + w).fadeIn(500);
			}
		);

	},
	selectImg : function(idx) {
		this.displayImg(this.result[idx]);
	}, 
	adjustImgSize : function(img) {
		var imgSize = {width : 104, height : 104};
		if(img.width() > this.maxImgSize.width || img.height() > this.maxImgSize.height) {
			if( (img.width() / img.height()) > (this.maxImgSize.width / this.maxImgSize.height) ) {
				imgSize.width =  this.maxImgSize.width;
				imgSize.height =  this.maxImgSize.width * ( img.height() / img.width());
			} else {
				imgSize.height =  this.maxImgSize.height;
				imgSize.width =  this.maxImgSize.height * ( img.width() / img.height());
			}
		} else {
			imgSize.width =  img.width();
			imgSize.height = img.height();
		}
		//return imgSize;
		img.width(imgSize.width);
		img.height(imgSize.height);
		
	},
	displayImg : function(selected) {
		this.layer.find(".pagination a.viewAll, .imgScreen a").attr("href", selected.imageUrl);
		var img = this.layer.find(".imgScreen img").get(0);
		
		if(img.style.display != "none") $(img).hide();
		var _this = this;
		
		$(img).height("auto");
		$(img).width("auto");
		
		$(img).unbind("load").load(function(event) {
			_this.adjustImgSize($(this));
			_this.loaded();
			$(this).fadeIn(500);
		});
		this.loading();
		img.src = selected.imageUrl;
	},
	loading : function() {
		this.loadingLayer.show();
	},
	loaded : function() {
		this.loadingLayer.hide();
	},
	prevPage : function() {
		if(this.page <= 1) return;
		this.page--;
		this.listImg();
	},
	nextPage : function() {
		if( this.pageCount <= this.page) return;
		this.page++;
		this.listImg();
	},
	close : function() {
		if(this.layer) {
			this.layer.remove();
			this.layer = null;
		}
		if(this.loadingLayer) {
			this.loadingLayer.remove();
			this.loadingLayer = null;
		}
	}
}
bugs.music.genreLayer = bugs.create();
bugs.music.genreLayer.prototype = {
	URL : "/artist/ajax/genredic",
	initialize : function() {
	},
	_load : function(data) {
		var _url = g_urlAjax + this.URL;
		$.get(_url, data, $.proxy(function(result) {
			if(typeof result != "string") return;
			if(typeof this.layer == "undefined") {
				this.layer = new bugs.ui.popup(result, {
					title : "장르/스타일 <span>사전</span>",
					css : "layerArtDic",
					onInit : function(popup) {},
					onOk : function(popup) {}
				});
				this.layer.show();
			} else {
				this.layer.innerHtml(result);
			}
			var _layer = this.layer.layer;
			var _this = this;
			this.layer.layer.find("select[name=genre_cd]").change(function(event) {
				_this.gload(this.value);
			}).end().find("select[name=pgenre_cd]").change(function(event) {
				_this.load(this.value);
			});
			
			this.layer.layer.find("div.aboutStyle ul li a").click(function(event){
				_this.load($(this).attr("genre_cd"));
			});
		}, this), "html");
	},
	load : function(pgenreCd) {
		if(typeof pgenreCd == "undefined" || pgenreCd == "") return;
		this._load({
			decorator : "blank",
			pcd : pgenreCd
		});
	},
	gload : function(genreCd) {
		if(typeof genreCd == "undefined" || genreCd == "") return;
		this._load({
			decorator : "blank",
			cd : genreCd
		});
	}
}

bugs.music.openGenreLayer = function(genreCd) {
	bugs.logging.add(3002, ["5"]);
	var genreLayer = new bugs.music.genreLayer();
	genreLayer.load(genreCd);
	$("div.layerPopup.layerArtDic").remove();
}


bugs.music.photoPageList = bugs.create(); 
bugs.music.photoPageList.prototype = {
	ROW_NUM : 3,
	initialize : function(url, data, clickFunc) {
		this.url = url;
		this.data = data;
		this.page = 1;
		this.row = this.ROW_NUM;
		this.clickFunc = clickFunc;
		this.imgList = $(".photoList ul li");
	},
	initData : function(callback) {
		if(typeof this.result == "undefined") {
			$.ajax({
				url : this.url,
				data : this.data,
				success : $.proxy(function(result) { 
					this.result = result;
					this.pageCount = bugs.math.ceil(result.length / this.row, 0);
					
					callback(result); 
				}, this),
				dataType : "json"
			});
		} else {
			callback(this.result);
		}
	},
	listImg : function() {
		$(".photoList ul li a").remove();
		var _this = this;
		var _clickFunc = this.clickFunc;
		this.imgList.each(function(idx) {
			var listIdx = idx + (_this.page-1)*_this.row;
			if(listIdx < _this.result.length) {
				$(this).click($.proxy(function(event) {
					event.preventDefault();
					_clickFunc(_this.result[listIdx]);
				}, _this)).append('<a href="javascript:void(0);"><img src="'+_this.result[listIdx].clip59+'" onerror="bugs.utils.imgError(this);" alt="" /><span class="thumbnailValign"></span><span class="over"></span></a>');
			}
		});
		
		this.imgList.find("a img").each(
			function() {
				var w = Math.floor(Math.random()*300);
				$(this).delay(300 + w).fadeIn(500);
			}
		);

	},
	pageButton : function() {
		if(this.page == 1) $(".photoList .btn.bcPrev").html('이전');
		else $(".photoList .btn.bcPrev").html('<a href="javascript:_photo.prevPage();">이전</a>');
		
		if(this.page == this.pageCount) $(".photoList .btn.bcNext").html('다음');
		else $(".photoList .btn.bcNext").html('<a href="javascript:_photo.nextPage();">다음</a>');
		
	},
	prevPage : function() {
		if(this.page <= 1) return;
		this.initData($.proxy(function(result) {
			this.page--;
			this.listImg();
			this.pageButton();
			
		}, this));
		
	},
	nextPage : function() {
		this.initData($.proxy(function(result) {
			if( this.pageCount <= this.page) return;
			this.page++;
			this.listImg();
			this.pageButton();
		}, this));
	}
}



bugs.music.artistFans = bugs.create();
bugs.music.artistFans.prototype = {
	PAGE_ROW : 4,
	TEMPLATE_HTML : '<ul class="listBox">' +
		'<% for(var i =0 ;i < obj.list.length; i++) { var item = obj.list[i]; if(typeof item.userInfo != "undefined" && item.userInfo != null) { %><li><div class="fanInfo">' +
		'	<span class="thumbnail"><img src="<%=item.userInfo.clipImg30%>" alt="<%=item.userInfo.nickname%>" onerror="bugs.utils.imgError(this);"/></span>'+
		'	<span class="username"><%=item.userInfo.nickname%></span> '+ 
		'</div></li><% } } %>' +
		'</ul>' +
		'<% if(obj.pageCount > 1) {%><div class="pagination">' +
		'	<span class="page"><%=obj.page%>/<%=obj.pageCount%></span>' +
		'	<span class="btnArea">' +
		'		<% if(obj.page > 1) {%> ' +
		'		<a href="javascript:void(0);" class="btnPagination bcPrev"><span>이전</span></a>' +
		'		<% } %> ' +
		'		<% if(obj.page < obj.pageCount) {%> ' +
		'		<a href="javascript:void(0);" class="btnPagination bcNext"><span>다음</span></a>' +
		'		<% } %> ' +
		'	</span>' +
		'</div><div class="btnClose"><a href="javascript:void($(\'.layerFan\').hide())"><span>닫기</span></a></div><% } %>',
	URL : g_urlMusic + "/artist/ajax/artistFans",
	initialize : function(total, artistId) {
		this.page = 1;
		this.pageCount = bugs.math.ceil(this.total / this.PAGE_ROW);
		this.box = $(".content.artistFan");
		this.artistId = artistId;
	},
	nextPage : function() {
		if(this.page >= this.pageCount) return;
		this.load(this.page + 1);
	},
	prevPage : function() {
		if(this.page <= 1) return;
		this.load(this.page - 1);
	}, 
	load : function(page) {
		$.get(g_urlMusic + "/artist/json/artistFans", {id : this.artistId, page : page, row : this.PAGE_ROW, decorator : "blank"}, $.proxy(function(result) {
			if(!result || !result.list) return;
			if(result.total == 0) {
				this.box.hide();
				return;
			}
			
			result.pageCount = bugs.math.ceil(result.total / this.PAGE_ROW);
			var temp = new bugs.template(this.TEMPLATE_HTML, result);
			$(" > ul, > div", this.box).remove();
			//alert(temp.html());
			var objResult = $(temp.html());
			var _this = this;
			objResult.find(".btnArea a").each(function() {
				var o = $(this);
				if(o.hasClass("bcPrev")) {
					o.click($.proxy(_this.prevPage, _this));
				} else if(o.hasClass("bcNext")) 
					o.click($.proxy(_this.nextPage, _this)); 
					
			});
			objResult.appendTo(this.box);
			if(result.total > 0)
				this.box.show();
			
			this.page = page;		
		}, this), "json");
		/*
		$.get(this.URL, {id : this.artistId, page : page, row : this.PAGE_ROW, decorator : "blank"}, $.proxy(function(result) {
			if(typeof result != "string" ) return;
			var list = $(result);
			//if(list.length == 0 || list.get(0).tagName != "LI") return;
			$(" > ul, > div", this.box).remove();
			
			$(result).appendTo(this.box);
			this.page = page;
			
			$("ul *", this.box).remove();
			$("ul", this.box).append(list);
			
			$(".pagination .page", this.box).text(this.page + "/" + this.pageCount);
			if(this.page >= this.pageCount) {
				$(".pagination .btnArea a:first", this.box).show();
				$(".pagination .btnArea a:last", this.box).hide();
			} else if(this.page <= 1) {
				$(".pagination .btnArea a:first", this.box).hide();
				$(".pagination .btnArea a:last", this.box).show();
			} else
				$(".pagination .btnArea a", this.box).show();
			
		}, this));
		*/
	}
} 

	

bugs.music.albumFans = bugs.create();
bugs.music.albumFans.prototype = {
	PAGE_ROW : 4,
	TEMPLATE_HTML : '<ul class="listBox">' +
		'<% for(var i =0 ;i < obj.list.length; i++) { var item = obj.list[i]; if(typeof item.userInfo != "undefined" && item.userInfo != null) { %><li><div class="fanInfo">' +
		'	<span class="thumbnail"><img src="<%=item.userInfo.clipImg30%>" alt="<%=item.userInfo.nickname%>" onerror="bugs.utils.imgError(this);"/></span>'+
		'	<span class="username"><%=item.userInfo.nickname%></span> '+ 
		'</div></li><% } } %>' +
		'</ul>' +
		'<% if(obj.pageCount > 1) {%><div class="pagination">' +
		'	<span class="page"><%=obj.page%>/<%=obj.pageCount%></span>' +
		'	<span class="btnArea">' +
		'		<% if(obj.page > 1) {%> ' +
		'		<a href="javascript:void(0);" class="btnPagination bcPrev"><span>이전</span></a>' +
		'		<% } %> ' +
		'		<% if(obj.page < obj.pageCount) {%> ' +
		'		<a href="javascript:void(0);" class="btnPagination bcNext"><span>다음</span></a>' +
		'		<% } %> ' +
		'	</span>' +
		'</div><div class="btnClose"><a href="javascript:void($(\'.layerFan\').hide())"><span>닫기</span></a></div><% } %>',
	URL : g_urlMusic + "/album/ajax/albumFans",
	initialize : function(total, albumId) {
		this.page = 1;
		this.pageCount = bugs.math.ceil(this.total / this.PAGE_ROW);
		this.box = $(".albumFan");
		this.albumId = albumId;
	},
	nextPage : function() {
		if(this.page >= this.pageCount) return;
		this.load(this.page + 1);
	},
	prevPage : function() {
		if(this.page <= 1) return;
		this.load(this.page - 1);
	}, 
	load : function(page) {
		$.get(g_urlMusic + "/album/json/albumFans", {id : this.albumId, page : page, row : this.PAGE_ROW, decorator : "blank"}, $.proxy(function(result) {
			if(!result || !result.list) return;
			if(result.total == 0) {
				this.box.hide();
				return;
			}
			
			result.pageCount = bugs.math.ceil(result.total / this.PAGE_ROW);
			var temp = new bugs.template(this.TEMPLATE_HTML, result);
			$(" > ul, > div", this.box).remove();
			var objResult = $(temp.html());
			var _this = this;
			objResult.find(".btnArea a").each(function() {
				var o = $(this);
				if(o.hasClass("bcPrev")) {
					o.click($.proxy(_this.prevPage, _this));
				} else if(o.hasClass("bcNext")) 
					o.click($.proxy(_this.nextPage, _this)); 
					
			});
			objResult.appendTo(this.box);
			if(result.total > 0)
				this.box.show();
			
			this.page = page;		
		}, this), "json");
	}
} 


bugs.music.recommend = bugs.create();
bugs.music.recommend.prototype = {
	PAGE_ROW : 3,	
	TEMPLATE_HTML_ARTIST : '<div class="otherInfo">' +
	'	<h5><span>벅스추천 아티스트</span><div class="btnAdvice"><a href="javascript:void($(\'.layerOther\').show())"><span>?</span></a></div></h5>' +
	'	<ul class="listBox">' +
	'<% for(var i =0 ;i < obj.list.length; i++) { var item = obj.list[i]; if(typeof item.artist != "undefined" && item.artist != null) { %><li><dl class="list">' +
	'	<dt class="artistname"><a href="<%=bugs.url.artistPage(item.artist.artist_id) %>" title="<%=item.artist.artist_nm%>" onclick="bugs.logging.add(900,[\'artist\',\'artist_name\'],0,false);"><%=item.artist.artist_nm%></a></dt> '+
	'	<dd class="thumbnail"><a href="<%=bugs.url.artistPage(item.artist.artist_id) %>" title="<%=item.artist.artist_nm%>" onclick="bugs.logging.add(900,[\'artist\',\'image\'],0,false);"><img src="<%=item.artist.clipImg59%>" alt="<%=item.artist.artist_nm%>" onerror="bugs.utils.imgError(this);"/><span class="thumbnailValign"></span></a></dd>'+
	'	<dd class="category"><%if(item.group_cd){%><%=item.group_cd%> <%}%> <%if(item.sex_cd) {%>(<%=item.sex_cd%>)<%}%></dd>' +
	'	<dd class="preference">	' +
	'	<% if(item.score >= 0.8) {%><span class="score5">1.00 ~ 0.8</span> ' +
	'	<% } else if(item.score >= 0.6) {%><span class="score4">0.79 ~ 0.6</span>' +
	'	<% } else if(item.score >= 0.4) {%><span class="score3">0.59 ~ 0.4</span>' +
	'	<% } else if(item.score >= 0.2) {%><span class="score2">0.39 ~ 0.2</span>' +
	'	<% } else { %><span class="score1">0.19 ~ 0.0</span><% } %>' +
	'	</dd>' +
	'</dl></li><% } } %>' +
	'</ul>' +
	'<% if(obj.pageCount > 1) {%><div class="pagination">' +
	'	<span class="page"><%=obj.page%>/<%=obj.pageCount%></span>' +
	'	<span class="btnArea">' +
	'		<% if(obj.page > 1) {%> ' +
	'		<a href="javascript:void(0);" class="btnPagination bcPrev"><span>이전</span></a>' +
	'		<% } %> ' +
	'		<% if(obj.page < obj.pageCount) {%> ' +
	'		<a href="javascript:void(0);" class="btnPagination bcNext"><span>다음</span></a>' +
	'		<% } %> ' +
	'	</span>' +
	'</div><% } %>' +
	'</div>',
	TEMPLATE_HTML_ALBUM : '<div class="otherInfo">' +
		'	<h5><span>벅스추천 앨범</span><div class="btnAdvice"><a href="javascript:void($(\'.layerOther\').show())"><span>?</span></a></div></h5>' +
		'	<ul class="listBox">' +
		'<% for(var i =0 ;i < obj.list.length; i++) { var item = obj.list[i]; if(typeof item.album != "undefined" && item.album != null) { %><li><dl class="list">' +
		'	<dt class="albumtitle"><a href="<%=bugs.url.albumPage(item.album.album_id)%>" title="<%=item.album.title%>" onclick="bugs.logging.add(900,[\'album\',\'title\'],0,false);"><%=item.album.title%></a></dt>'+
		'	<dd class="thumbnail"><a href="<%=bugs.url.albumPage(item.album.album_id) %>" title="<%=item.album.title%>" onclick="bugs.logging.add(900,[\'album\',\'image\'],0,false);"><img src="<%=item.album.clipImg59%>" alt="<%=item.album.title%>" onerror="bugs.utils.imgError(this);"/><span class="thumbnailValign"></span></a></dd>'+
		'	<dt class="artistname"><a href="<%=bugs.url.artistPage(item.album.artist_id) %>" title="<%=item.album.artist_nm%>" onclick="bugs.logging.add(900,[\'album\',\'artist_name\'],0,false);"><%=item.album.artist_nm%></a></dt> '+ 
		'	<dd class="preference">	' +
		'	<% if(item.score >= 0.8) {%><span class="score5">1.00 ~ 0.8</span>' +
		'	<% } else if(item.score >= 0.6) {%><span class="score4">0.79 ~ 0.6</span>' +
		'	<% } else if(item.score >= 0.4) {%><span class="score3">0.59 ~ 0.4</span>' +
		'	<% } else if(item.score >= 0.2) {%><span class="score2">0.39 ~ 0.2</span>' +
		'	<% } else {%><span class="score1">0.19 ~ 0.0</span><% } %>' +
		'	</dd>' +
		'</dl></li><% } } %>' +
		'</ul>' +
		'<% if(obj.pageCount > 1) {%><div class="pagination">' +
		'	<span class="page"><%=obj.page%>/<%=obj.pageCount%></span>' +
		'	<span class="btnArea">' +
		'		<% if(obj.page > 1) {%> ' +
		'		<a href="javascript:void(0);" class="btnPagination bcPrev"><span>이전</span></a>' +
		'		<% } %> ' +
		'		<% if(obj.page < obj.pageCount) {%> ' +
		'		<a href="javascript:void(0);" class="btnPagination bcNext"><span>다음</span></a>' +
		'		<% } %> ' +
		'	</span>' +
		'</div><% } %>' +
		'</div>',
	initialize : function(type, id) {
		this.type = type;
		this.page = 1;
		this.id = id;
		this.URL = g_urlMusic + "/" + this.type + "/json/recommend";
		this.box = $("#recommend");
		if(this.type=="artist") this.template = this.TEMPLATE_HTML_ARTIST;
		else this.template = this.TEMPLATE_HTML_ALBUM;

		this.load(this.page);
	},
	nextPage : function() {
		if(this.page >= this.pageCount) return;
		this.load(this.page + 1);
		
		bugs.logging.add(900,[this.type,"paging"],0,false);
	},
	prevPage : function() {
		if(this.page <= 1) return;
		this.load(this.page - 1);
		
		bugs.logging.add(900,[this.type,"paging"],0,false);
	}, 
	load : function(page) {
		$.get(this.URL, {id : this.id, page : page, row : this.PAGE_ROW}, $.proxy(function(result) {
			if(!result || !result.list) return;

			if(result.total == 0) {
				this.box.hide();
				return;
			}

			result.pageCount = bugs.math.ceil(result.total / this.PAGE_ROW);
			var temp = new bugs.template(this.template, result);

			$(" > div", this.box).remove();
			var objResult = $(temp.html());
			var _this = this;
			
	
			objResult.find(".btnArea a").each(function() {
				var o = $(this);
				if(o.hasClass("bcPrev")) {
					o.click($.proxy(_this.prevPage, _this));
				} else if(o.hasClass("bcNext")) 
					o.click($.proxy(_this.nextPage, _this)); 
					
			});
			objResult.appendTo(this.box);
			if(result.total > 0)this.box.show();

			this.page = page;		
		
		}, this), "json");
	}
} 

	
bugs.music.subAlbum = bugs.create();
bugs.music.subAlbum.prototype = {
	PAGE_ROW : 3,
	TEMPLATE_HTML : '<ul class="recommendAlbum">' +
		'<% for(var i =0 ;i < obj.list.length; i++) { var item = obj.list[i]; if(typeof item.album != "undefined" && item.album != null) { %><li>' +
		'<div class="thumbnail"><a href="<%=bugs.url.albumPage(item.album.album_id)%>"><img src="<%=item.album.clipImg75%>" alt="<%=item.album.title%>" onerror="bugs.utils.imgError(this);" /><span class="thumbnailValign"></span></a></div>'+
		'<dl class="albumInfo" style="background:#F00;">'+
		'	<dt class="ellipsis"><a href="<%=bugs.url.albumPage(item.album.album_id)%>" class="albumtitle"><%=item.album.title%></a></dt> '+ 
		'	<dd><a href="<%=bugs.url.artistPage(item.album.artist_id)%>" class="artistname"><%=item.album.artist_nm%></a></dd>'+
		'	<dd class="titleSong"><strong>타이틀곡</strong> : <% if(item.album.titleTrack) {%><a href="<%=bugs.url.trackPage(item.album.titleTrack.track_id)%>"><%=item.album.titleTrack.track_title%></a><% }%></dd>'+
		'	<dd class="date"><%=item.album.release_ymd.substring(0,4)%><%if(item.album.release_ymd.length>4){%>.<%=item.album.release_ymd.substring(4,6)%><%} if(item.album.release_ymd.length>6){%>.<%=item.album.release_ymd.substring(6,8)%><%}%></dd>'+
		'</dl></li><% } } %>' +
		'</ul>' +
		'<% if(obj.pageCount > 1) {%><div class="pagination">' +
		'	<span class="page"><%=obj.page%>/<%=obj.pageCount%></span>' +
		'	<span class="btnArea">' +
		'		<% if(obj.page > 1) {%> ' +
		'		<a href="javascript:void(0);" class="btnPagination bcPrev"><span>이전</span></a>' +
		'		<% } %> ' +
		'		<% if(obj.page < obj.pageCount) {%> ' +
		'		<a href="javascript:void(0);" class="btnPagination bcNext"><span>다음</span></a>' +
		'		<% } %> ' +
		'	</span>' +
		'</div><% } %>',
	URL : g_urlMusic + "/album/ajax/albumFans",
	initialize : function(total, albumId) {
		this.page = 1;
		this.pageCount = bugs.math.ceil(this.total / this.PAGE_ROW);
		this.box = $(".servicesLimited");
		this.albumId = albumId;
	},
	nextPage : function() {
		if(this.page >= this.pageCount) return;
		this.load(this.page + 1);
	},
	prevPage : function() {
		if(this.page <= 1) return;
		this.load(this.page - 1);
	}, 
	load : function(page) {
		$.get(g_urlMusic + "/album/json/subAlbum", {id : this.albumId, page : page, row : this.PAGE_ROW, decorator : "blank"}, $.proxy(function(result) {
			if(!result || !result.list) return;
			if(result.total == 0) {
				this.box.hide();
				return;
			}
			
			result.pageCount = bugs.math.ceil(result.total / this.PAGE_ROW);
			var temp = new bugs.template(this.TEMPLATE_HTML, result);
			$(" > ul, > div", this.box).remove();
			var objResult = $(temp.html());
			var _this = this;
			objResult.find(".btnArea a").each(function() {
				var o = $(this);
				if(o.hasClass("bcPrev")) {
					o.click($.proxy(_this.prevPage, _this));
				} else if(o.hasClass("bcNext")) 
					o.click($.proxy(_this.nextPage, _this)); 
					
			});
			objResult.appendTo(this.box);
			if(result.total > 0)
				this.box.show();
			
			this.page = page;		
		}, this), "json");
	}
}; 



bugs.music.musicVideos = bugs.create();
bugs.music.musicVideos.prototype = {
	PAGE_ROW : 3,
	initialize : function(total, trackId) {
		this.page = 1;
		this.pageCount = bugs.math.ceil(this.total / this.PAGE_ROW);
		this.trackId = trackId;
		this.type = "TRACK";
	},
	nextPage : function() {
		if(this.page >= this.pageCount) return;
		this.page++;
		this.load(this.page);
	},
	prevPage : function() {
		if(this.page <= 1) return;
		this.page--;
		this.load(this.page);
	}, 
	load : function(page) {
		$.get(g_urlMusic + "/mv/ajax/list2", {id : this.trackId, type : this.type, page : page, row : this.PAGE_ROW}, function(result) {
			if(!result) return;
			
			$(".otherInfo").html(result);
		});
	}
} 

